/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.modules.commission;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.jfinal.log.Logger;
import com.koorz.modules.style.Style;
import com.koorz.utils.DateUtil;
import com.koorz.utils.SystemConfig;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.TaobaokeReport;
import com.taobao.api.domain.TaobaokeReportMember;
import com.taobao.api.request.TaobaokeReportGetRequest;
import com.taobao.api.response.TaobaokeReportGetResponse;

/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-6-14 下午4:59:22
 * 版  本  号：1.0
 */
public class ReportJob implements Runnable {
	protected final Logger logger = Logger.getLogger(getClass());
	//淘宝只能获取1-499页数据
	private long maxPage = 499;
	//默认是40条.最大每页100
	private long pageSize = 20;
	private String fields = "trade_id,real_pay_fee," +
			"commission_rate,commission,outer_code,create_time,pay_time,pay_price,num_iid,item_title,item_num";
	@Override
	public void run() {
		TaobaoClient client = new DefaultTaobaoClient(
				SystemConfig.getValue("taobao_baseURL"), SystemConfig.getValue("taobao_client_ID"),
				SystemConfig.getValue("taobao_client_SERCRET"));
		long totalResults = 0;
		long page = 1;
		long totalPage = 0;
		while (true) {
			TaobaokeReportGetRequest request = new TaobaokeReportGetRequest();
			request.setDate(StringUtils.replace(DateUtil.getDayAdd(new Date(), -1), "-", ""));
			request.setFields(fields);
			request.setPageNo(page);
			request.setPageSize(pageSize);
			try {
				TaobaokeReportGetResponse response = client.execute(request);
				TaobaokeReport report = response.getTaobaokeReport();
				//第一次计算
				if(totalResults == 0){
					totalResults = report.getTotalResults();
				}
				
				List<TaobaokeReportMember> memberList = report.getTaobaokeReportMembers();
				if(memberList != null && memberList.size() > 0){
					for(TaobaokeReportMember member:memberList){
						OrderForm orderForm = OrderForm.dao.findFirst("select * from order_form where trade_id=?", member.getTradeId());
						if(orderForm == null){
							orderForm = new OrderForm();
							orderForm.set("trade_id", member.getTradeId()+"");
							orderForm.set("real_pay_fee", member.getRealPayFee());
							orderForm.set("commission_rate", member.getCommissionRate());
							orderForm.set("commission", member.getCommission());
							orderForm.set("create_time", DateUtil.getDate(member.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
							orderForm.set("pay_time", DateUtil.getDate(member.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
							orderForm.set("pay_price", member.getPayPrice());
							orderForm.set("num_iid", member.getNumIid()+"");
							orderForm.set("item_title", member.getItemTitle());
							orderForm.set("item_num", member.getItemNum());
							if(StringUtils.isNotEmpty(member.getOuterCode())){
								orderForm.set("outer_code", member.getOuterCode());
								Style style = Style.dao.findById(member.getOuterCode());
								if(style != null){
									orderForm.set("style_id", style.getStr("id"));
									orderForm.set("user_id", style.getStr("user_id"));
								}
							}
							OrderForm.saveOrderForm(orderForm);
						}
					}
				}
			} catch (ApiException e) {
				logger.error("ReportJob-淘宝报表任务异常：", e);
			}
			page++;
			
			//第一次计算
			if(totalPage == 0){
				totalPage = totalResults / pageSize;
				if (totalResults % pageSize != 0) {
					totalPage++;
				}
			}
			
			if(page > totalPage || page > maxPage){
				break;
			}
		}
	}

}
